package com.lihepeng.leecode.juc;

public class FooBar {
    private int n;
    private volatile Integer status = 0;
    private Object lock = new Object();
    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            synchronized (lock) {
                if (status !=0) {
                    lock.wait();
                }
                // printFoo.run() outputs "foo". Do not change or remove this line.
                printFoo.run();
                status =1;
                lock.notifyAll();
            }

        }

    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            synchronized (lock) {
                if (status ==0) {
                    lock.wait();
                }
                printBar.run();
                status =0;
                lock.notifyAll();
            }

        }

    }
}
